﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.IO;
using System.Windows.Forms;

namespace SenseUtil
{
    static public class TabFileBuilder
    {
        const string CSTR_TemplateFile = "ManilaTemplate";
        const string CSTR_TempFile = "Temp";
        static public string BuildSenseListFile(List <string> fileReference, List <int> indexReference, string targetfile)
        {
            //For now assume that all tabs will be generated from the information in the avilable tab files
            //But in the order of the Tabs (Loaded) list
            //Any tabs which are missing (99="") will be skipped - perhaps "COREFIXED" items can be flagged
            //with "" to indicate copy from original file.

            //Create and Open the test file
            string targetFilename = Settings.GetApplicationPathOnly() + targetfile + TabList.CSTR_FileExt;
            string tempFilename = Settings.GetApplicationPathOnly() + CSTR_TempFile + TabList.CSTR_FileExt;
            string templatefile = Settings.GetApplicationPathOnly() + TabList.CSTR_ResourcePath + CSTR_TemplateFile + TabList.CSTR_FileExt;
            //Check to see if file exists
            if (File.Exists(targetFilename))
            {
                //Delete old file
                File.Delete(targetFilename);
            }
            //Check to see if file exists
            if (File.Exists(tempFilename))
            {
                //Delete old file
                File.Delete(tempFilename);
            }

            //Initialise a new file
            //System.Xml.Linq.XDocument db = new System.Xml.Linq.XDocument(new System.Xml.Linq.XElement("Manila"));
            if (File.Exists(templatefile))
            {
                XmlDocument db = new XmlDocument();
                db.Load(templatefile);

                //Add tab entries into file
                int i = 0;
                foreach (string tabfilename in fileReference)
                {
                    string fullFilename;

                    //If filename is blank, then assume tab taken from original source file
                    if (tabfilename == "")
                    {
                        //Set the filename equal to the original tab control file
                        fullFilename = TabControlFile.CSTR_WindowsPath + TabControlFile.CSTR_TabControlFilename;
                    }
                    else
                    {
                        //Set to filename equal to the related tab xml file
                        fullFilename = Settings.GetApplicationPathOnly() + TabList.CSTR_ResourcePath + tabfilename + TabList.CSTR_FileExt;
                    }

                    //check file exists
                    if (File.Exists(fullFilename))
                    {
                        try
                        {
                            //Fetch Manila Node from tab file
                            //Open as xml document for processing
                            XmlDocument xmldoc = new XmlDocument();
                            xmldoc.Load(fullFilename);
                            
                            // Locate the root node and 
                            // Create a list of the child nodes of "Manila"
                            XmlNodeList nodelist = xmldoc.DocumentElement.GetElementsByTagName("Page");

                            XmlNode theNode = null;
                            if ((nodelist != null) && (nodelist.Count > indexReference[i]))
                            {
                                theNode = nodelist[indexReference[i]];
                            }

                            //Update the node Page Order
                            if (theNode != null)
                            {
                                //Import the node ready to copy
                                XmlNode addNode = db.ImportNode(theNode, true);

                                if (addNode.Attributes.GetNamedItem("Order") != null)
                                {
                                    addNode.Attributes.GetNamedItem("Order").Value = i.ToString();
                                }

                                //Find point to insert the file
                                XmlNodeList nodes = db.GetElementsByTagName("PageGroup");
                                //Check each node for Name="Root"
                                foreach (XmlNode aNode in nodes)
                                {
                                    if (aNode.Attributes.Count > 0)
                                    {
                                        if (aNode.Attributes.GetNamedItem("Name") != null)
                                        {
                                            if (aNode.Attributes.GetNamedItem("Name").Value == "Root")
                                            {
                                                aNode.AppendChild(addNode);
                                                i++;
                                            }
                                        }
                                    }
                                }
                                
                            }
                        }
                        catch
                        {
                            MessageBox.Show("Unable to process file " + tabfilename);
                            targetFilename = "";
                        }
                    }
                }

                //Save the target file
                db.Save(tempFilename);

                //Convert the file
                ConvertUFT8ToUTF16(tempFilename, targetFilename);

                //Delete temp file
                if(File.Exists(tempFilename))
                {
                    File.Delete(tempFilename);
                }

            }
            return (targetFilename);
        }

        private static void ConvertUFT8ToUTF16(string sourcefilename, string targetfilename)
        {
            using (StreamWriter output = new StreamWriter(targetfilename, false, Encoding.Unicode))
            {
                using (StreamReader input = new StreamReader(sourcefilename))
                {
                    while (input.EndOfStream == false)
                    {
                        string utf8string = input.ReadLine();
                        output.WriteLine(utf8string);
                    }
                    output.Flush();
                    output.Close();
                }
            }
        }

        public static bool isGeneratedFilePresent(string filename)
        {
            bool present = false;
            //Check to see if file is present
            if (File.Exists(filename))
            {
                present = true;
            }

            return present;
        }
    }
}
